package com.wpml.orm;

import com.wpml.po.UcUser;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Arrays;
import java.util.Date;

public interface OrmHandler<T> {
    /**
     * 处理返回结果集
     * @return
     */
    T handler(ResultSet rs) throws Exception;


    default T column2Property(ResultSet resultSet, Class<T> clazz) throws Exception{
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        Field[] declaredFields = clazz.getDeclaredFields();

        int[] column2Property = new int[columnCount + 1];
        Arrays.fill(column2Property, -1); // 初始化数组值为 -1
        // 找到查询列与对象属性之间对应关系
        for (int i = 1; i < columnCount + 1; i++) {
            for (int j = 0; j < declaredFields.length; j++) {
                if (metaData.getColumnName(i).equalsIgnoreCase(declaredFields[j].getName())) {
                    column2Property[i] = j;
                }
            }
        }

        T newInstance = clazz.newInstance();
        if (resultSet.next()) {
            for (int i = 1; i < column2Property.length; i++) {
                if (column2Property[i] != -1) {
                    Field field = declaredFields[column2Property[i]];
                    field.setAccessible(true);
                    Class<?> type = field.getType();
                    if (type == Integer.class || type == Integer.TYPE) {
                        field.set(newInstance, resultSet.getInt(i));
                    } else if (type == String.class) {
                        field.set(newInstance, resultSet.getString(i));
                    } else if (type == Long.class || type == Long.TYPE) {
                        field.set(newInstance, resultSet.getLong(i));
                    } else if (type == Byte.class || type == Byte.TYPE) {
                        field.set(newInstance, resultSet.getByte(i));
                    } else if (type == BigDecimal.class) {
                        field.set(newInstance, resultSet.getBigDecimal(i));
                    } else if (type == Date.class) {
                        field.set(newInstance, resultSet.getDate(i));
                    } else if (type == Object.class) {
                        field.set(newInstance, resultSet.getObject(i));
                    }
                }
            }
        }
        return newInstance;
    }
}
